package tool;

import javax.servlet.*;
import java.io.IOException;
import java.util.Date;

public class CustomFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("初始化过滤器");
    }

    /** 为某些或特定servlet设置请求的编码和响应的内容类型 */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        System.out.println("执行过滤");
        servletRequest.setCharacterEncoding("UTF-8");
        servletResponse.setContentType("text/html;charset=UTF-8");
        filterChain.doFilter(servletRequest, servletResponse);
        String ip = servletRequest.getRemoteAddr();
        Date time = new Date();
        // 在服务器端打印执行请求或响应的internet协议地址和具体时间
        servletRequest.getServletContext().log(ip + time);
    }

    @Override
    public void destroy() {
        System.out.println("销毁过滤器");
    }
}
